/**
  ******************************************************************************
  * File Name          : sgp30.c
  * Description        : This file provides code for the configuration
  *                      of the lora e22-400t22s instances.
  ******************************************************************************
  * @attention
  *
  ******************************************************************************
  */
#include "tskcfg.h"
#include "bsp.h"
#include "sensor.h"
#include "edct.h"
#include "si2c_comm.h"

/* TVOC CO2 Sensor task */
TaskHandle_t xSgp30_Thd = NULL;
StaticTask_t xSgp30_Tcb;
StackType_t  xSgp30_Stk[ SGP30_STACK_SIZE ];
void vSgp30_Task( void * pvParameters );

typedef struct
{
	volatile uint16_t co2;
	volatile uint16_t tvoc;
}SGP30_DataType;

static uint8_t sgp30_check_rational(uint16_t co2, uint16_t tvoc)
{
	if(co2 > 60000)
	{
		return 1;
	}
	
	if(tvoc > 60000)
	{
		return 2;
	}

	return 0;
}

static void sgp30_measure(void)
{
	uint8_t err;
  static uint8_t fail_sgp30 = 0;
  uint8_t active_sgp30 = 0;
	volatile SGP30_DataType sgp30_data;
  
  err = Sgp30_GetSingleMeasure(&sgp30_data.co2, &sgp30_data.tvoc);
  if(err == 0)
  {
    active_sgp30 = 1;
    fail_sgp30 = 0;
  }
  else
  {
    active_sgp30 = 0;
    fail_sgp30++;
    printf("sgp30 err:%d\r\n", err);
  }
  
  if((active_sgp30 != 0) && (sgp30_check_rational(sgp30_data.co2, sgp30_data.tvoc) == 0))
  {
    SENSOR.Status_CO2  = 1;
    SENSOR.Status_TVOC = 1;
    SENSOR.co2         = sgp30_data.co2;
    SENSOR.tvoc        = sgp30_data.tvoc;
  }
  else
  {
    SENSOR.co2  = 0;
    SENSOR.tvoc = 0;
  }
  
	if((fail_sgp30 == 10) || (fail_sgp30 == 15) || (fail_sgp30 == 20))
	{
    Sgp30_ResetCmd();
    
    Sgp30_ReInit();
    
    printf("SGP30 Soft reset!\r\n");
  }
  else if(fail_sgp30 > 29)
  {
    SENSOR.Status_CO2  = 0;
		SENSOR.Status_TVOC = 0;
		SENSOR.co2         = 0;
		SENSOR.tvoc        = 0;
    
//    Sgp30_ReInit();

    fail_sgp30 = 0;
	}
}

void vSgp30_Task( void * pvParameters )
{
  TickType_t xLastWakeTime;
  
  xLastWakeTime = xTaskGetTickCount();
  
	while(1)
	{
    if(xTaskDelayUntil(&xLastWakeTime, 1000) == pdFALSE)
    {
      vTaskDelay(1000);
      xLastWakeTime = xTaskGetTickCount();
    }
    
    if(Edct_RunPara.tvoc_en == 1)
    {
      sgp30_measure();
    }
	}
}
